package com.mibotiquin.alarmas;

import java.util.Calendar;

import com.mibotiquin.DbHelper.BaseUtil;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;

public class CadNot extends Activity{
	
	private Calendar calNot;
	private Calendar calRem;
	private Integer id;
	private String idM;
	private Boolean show = true;
	private Boolean remove = true;
	private String name;
	private Activity ref = null;
	
	
	public CadNot(String idM, String name, int month, int year, Activity ref) {
		
		this.ref = ref;
		
		//TODO: Comprobar si en la base de datos existe una notificaci?n con el mismo medicamento y modificarla en tal caso
		
		calNot = Calendar.getInstance();
		calNot.set(year, month, 1);
		
		calRem = Calendar.getInstance();
		calRem.set(year, month, 0);
		int day = calRem.getActualMaximum(Calendar.DAY_OF_MONTH);
		calRem.set(year, month, day);
		
		this.name = name;
		this.idM = idM;
		id = Integer.parseInt(idM);
		
	}
	
	public void init() {
		
		final BaseUtil bd = BaseUtil.getInstance(this);
		String[] data = {id.toString(), idM, name, calNot.get(Calendar.MONTH) + "/" + calNot.get(Calendar.YEAR), show.toString(), remove.toString()};
		ItemCad item = new ItemCad(data);
		bd.insertar(item);
		
		AlarmManager am = (AlarmManager)ref.getSystemService(Activity.ALARM_SERVICE);
		Intent intent = new Intent(ref, CadNotice.class);
		Bundle bundle = new Bundle();
		bundle.putInt("ID", id);
		bundle.putBoolean("SHOW", true);
		bundle.putBoolean("REM", false);
		intent.putExtras(bundle);
		PendingIntent sender = PendingIntent.getActivity(ref, id, intent, PendingIntent.FLAG_CANCEL_CURRENT);
		
		am.set(AlarmManager.RTC_WAKEUP, calNot.getTimeInMillis(), sender);
		
		intent = new Intent(ref, CadNotice.class);
		bundle = new Bundle();
		bundle.putInt("ID", id*100);
		bundle.putBoolean("SHOW", false);
		bundle.putBoolean("REM", true);
		intent.putExtras(bundle);
		sender = PendingIntent.getActivity(ref, id*100, intent, PendingIntent.FLAG_CANCEL_CURRENT);
		
		am.set(AlarmManager.RTC_WAKEUP, calRem.getTimeInMillis(), sender);
			
	}
	
	public void cancel() {
		
		AlarmManager am = (AlarmManager)ref.getSystemService(Activity.ALARM_SERVICE);
		Intent intent = new Intent(ref, CadNotice.class);
		PendingIntent sender = PendingIntent.getActivity(ref, id, intent, PendingIntent.FLAG_CANCEL_CURRENT);
		am.cancel(sender);
		
		intent = new Intent(ref, CadNotice.class);
		sender = PendingIntent.getActivity(ref, id*100, intent, PendingIntent.FLAG_CANCEL_CURRENT);
		am.cancel(sender);
		
		String query = "idM="+idM;
		final BaseUtil bd = BaseUtil.getInstance(this);
		ItemCad item = new ItemCad();
		bd.deleteItem(item, query);
		
	}

}
